package com.创建型模型.D单例模式;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**通过反射破坏单例
 * @author zhangjiawen
 * @Date: 2022/6/1 11:12
 */
public class LazyManReflec1 {

    public volatile static LazyManReflec1 lazyMan=null;

    private volatile static boolean zjw=false;

    private LazyManReflec1(){
        //1.防止破坏
     /*   synchronized (LazyManReflec1.class){
            if (lazyMan!=null){
                throw new RuntimeException("别想反射破坏单例");
            }
        }*/

     //2.添加标志位防止
        synchronized (LazyManReflec1.class) {
            if (zjw) {
                throw new RuntimeException("别想反射破坏单例2");
            } else {
                zjw = true;
            }
        }


    }


    public static LazyManReflec1 getInstance(){
        if (lazyMan==null){

            synchronized (LazyManReflec1.class){
                if (lazyMan==null) {
                    lazyMan = new LazyManReflec1();
                }
            }
        }

        return lazyMan;

    }


    public static void main(String[] args) throws Exception {

        //LazyManReflec1 lazyManReflec1=LazyManReflec1.getInstance();
        //1应付第一种 都通过反射生成
        Constructor<LazyManReflec1> declaredConstructor = LazyManReflec1.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        LazyManReflec1 lazyManReflec1 = declaredConstructor.newInstance();

        //2应付第二种  拿到标志位设为false
        Field zjw = LazyManReflec1.class.getDeclaredField("zjw");
        zjw.setAccessible(true);
        zjw.setBoolean(lazyManReflec1,false);
        LazyManReflec1 lazyManReflec2 = declaredConstructor.newInstance();


        System.out.println(lazyManReflec1);
        System.out.println(lazyManReflec2);


    }

}
